package com.zpq.jspTemplate;

import java.io.IOException;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;


/**
 * 将页面动态编译进来，类似于 <jsp:include />
 * @author tianya
 */
public class PageTag extends TagSupport {

    private static final long serialVersionUID = 1L;
    private String name;
    private String value;
    
    @Override
    public int doStartTag() throws JspException {
        @SuppressWarnings("unchecked")
        Map<String, Object> overrideMap = (Map<String, Object>) pageContext.getAttribute(
                Utils.getTemplateParamName("overrideMap"), PageContext.REQUEST_SCOPE);
        if (overrideMap == null) {
            // 直接访问模版
        	if (value != null) {
        		try {
					pageContext.getOut().write(value);
				} catch (IOException e) {
		            throw new JspException("write overridedContent occer IOException,override name:"+name,e);
				}
        		return SKIP_BODY;
			}
            return EVAL_PAGE;
        }
        
        String blockName = Utils.getTemplateParamName(name);    // 系统产生的 page name, __jsp_template__XXX
        
        Object overriedContent = overrideMap.get(blockName);
        if(overriedContent == null) {
            return EVAL_PAGE;
        }
        
        try {
            pageContext.getOut().write(overriedContent.toString());
        } catch (IOException e) {
            throw new JspException("write overridedContent occer IOException,override name:"+name,e);
        }
        overrideMap.remove(blockName);
        return SKIP_BODY;
    }
    
    
    @Override
    public void release() {
        super.release();
        name = null;
        value = null;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
    
}
